package com.mydesign.demo.Handler;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mydesign.demo.util.JWTUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String> map=new HashMap<>();
        String token = request.getHeader("token");
        try{
            JWTUtils.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","-1");
        }
        String json=new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
